package main

import (
	"MyDemo/MyZinx/znet"
	"fmt"
	"io"
	"net"
	"time"
)

/*
	模拟客户端
*/

func main() {
	fmt.Println("client start...")

	time.Sleep(1 * time.Second)

	conn, err := net.Dial("tcp", "127.0.0.1:8999")
	if err != nil {
		fmt.Println("client start err, exit!")
	}

	for {
		dp := znet.NewDataPack()
		binaryMsg, err := dp.Pack(znet.NewMsgPackage(1, []byte("ZinxV0.6 client1 Test Message")))
		if err != nil {
			fmt.Println("Pack error: ", err)
			return
		}

		if _, err := conn.Write(binaryMsg); err != nil {
			fmt.Println("write err: ", err)
			return
		}

		headData := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(conn, headData); err != nil {
			fmt.Println("read head err: ", err)
			break
		}
		msgHead, err := dp.UnPack(headData)
		if err != nil {
			fmt.Println("client unpack msghead err: ", err)
			break
		}

		if msgHead.GetMsgLen() > 0 {
			msg := msgHead.(*znet.Message)
			data := make([]byte, msg.GetMsgLen())
			msg.SetMsgData(data)

			if _, err := io.ReadFull(conn, msg.GetMsgData()); err != nil {
				fmt.Println("read data err: ", err)
				return
			}

			fmt.Println("----> Recv Server Msg: id=", msg.GetMsgId(), " len=", msg.GetMsgLen(), " data=", string(msg.GetMsgData()))
		}

		time.Sleep(1 * time.Second)
	}
}
